package com.guang.springbootone.controller;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;

/**
 * Logger 管理
 * @author springdoc.cn
 * 动态修改springboot中的日志级别：https://springdoc.cn/spring-boot-update-logger-level/
 */
@RestController
@RequestMapping("/loggers")
public class LoggerController {

    // Logger
    // 注意，这里使用的是 org.slf4j.Logger 接口
    static final org.slf4j.Logger log = LoggerFactory.getLogger(LoggerController.class);

    /**
     * 查看logger列表
     * @return
     */
    @GetMapping
    public ResponseEntity<List<Map<String, String>>> loggers() {
        
        // 获取到 LoggerContext
        LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
        
        // 获取系统中定义的所有 logger
        List<Map<String, String>> loggers = loggerContext.getLoggerList().stream().map(logger -> {
            // 映射为 Map，key 是 logger 名称，value 是其日志级别
            // logger名称 = logger有效级别
            return Collections.singletonMap(logger.getName(), logger.getEffectiveLevel().levelStr);
        }).collect(Collectors.toList());
        
        return ResponseEntity.ok(loggers);
    }

    /**
     * 修改日志级别
     * @param name
     * @param level
     * @return
     */
    @PostMapping
    public ResponseEntity<Object> setLevel(@RequestParam("name") String name,
                            @RequestParam("level") String level) {
        
        // 获取到 LoggerContext
        LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
        
        // 根据指定的名称获取 logger
        Logger logger = loggerContext.exists(name);
        if (logger == null) {
            return ResponseEntity.badRequest().body(name + " 日志记录器不存在");
        }
        
        // 解析 level 参数，第二个参数表示当 level 参数非法时的默认值
        Level newLevel = Level.toLevel(level, null);
        
        if (newLevel == null) {
            return ResponseEntity.badRequest().body(level + " 不是合法的日志级别");
        }
        
        // 重写设置 logger 的 level
        logger.setLevel(newLevel);
        
        return ResponseEntity.noContent().build();
    }

    /**
     * 测试日志输出
     * @return
     */
    @GetMapping("/test")
    public ResponseEntity<Void> test (){
        
        log.debug("Hello springdoc.cn");
        log.info("Hello springdoc.cn");
        log.warn("Hello springdoc.cn");
        log.error("Hello springdoc.cn");
        
        return ResponseEntity.noContent().build();
    }
}